/*
 * @Description: 捕捉错误中间件处理
 * @Author: lgt
 * @Date: 2021-06-27 10:24:00
 * @LastEditTime: 2021-06-27 11:32:17
 * @LastEditors: xxx
 */

 const {HttpException} = require("../core/http-exception")

//中间件使用async/await 保证洋葱模型
 const catchError = async(ctx,next)=>{
     try{
         await next();
     }catch(error){
         //判断是否是已知错误
         const isHttpException = error instanceof HttpException;
        
        //生产环境显示所有异常信息
        const isDev = global.config.environment === 'dev'
        if (isDev && !isHttpException) {
                    throw error
        }


         if(isHttpException){
             //是已知错误，
             ctx.body = {
                msg: error.msg,
                error_code: error.errorCode,
                request: `${ctx.method} ${ctx.path}`
            }
            ctx.status = error.code
         }else{
             //未知错误
            ctx.body = {
                msg: "未知错误！",
                error_code: 9999,
                request: `${ctx.method} ${ctx.path}`
            }
            ctx.status = 500
         }
     }
 }

module.exports = catchError